package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;

import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;
import svgedit.gui.SVGZFileFilter;

/** Shows discard changes dialog, then presents a file dialog for the
 *  user to select an existing document to edit.
 */
@SuppressWarnings("serial")
public class OpenDocumentAction extends AbstractAction {

    private Frame frame;

    /** Create this action for the given frame */
    public OpenDocumentAction(Frame frame) {
        super("Open...");
        this.frame = frame;
    }

    /**
     *  Open the document
     *  
     *  @param ae to monitor the action event
     * */
    public void actionPerformed(ActionEvent ae) {
        if (frame.confirmSaveChanges()) {
            String directory = frame.getPreferences().getDefaultPath();
            JFileChooser dialog = new JFileChooser(directory);
            dialog.addChoosableFileFilter(new SVGFileFilter());
            dialog.addChoosableFileFilter(new SVGZFileFilter());
            dialog.showOpenDialog(null);

            File file = dialog.getSelectedFile();
            if (file != null) {
            	frame.getPreferences().setDefaultPath(file.getPath());
            	// Remove temp file
            	if(frame.getTempfile() != null){
            		frame.getTempfile().delete();
            		frame.setTempfile(null);
            	}
            	// To read svgz file
            	if(dialog.getFileFilter().getDescription().equals("SVGZ Files")||file.getName().trim().toLowerCase().endsWith(".svgz")){
            		try {
						readSVGZ(file);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						System.out.println("Read svgz file fails");
					}
            	}else{
            		 frame.openFile(file);
            	}
                
            }
        }
    }
   
    /**
     *   Read file with extension of svgz which means the file is a compressed file
     *   
     *   @param file to get the file needs to be read
     *   @throws FileNotFoundException when file is not found, throw the exception
     *   @throws IOException when read and writer fails ,throw the exception
     * */
    public void readSVGZ(File file) throws FileNotFoundException, IOException{
    	FileInputStream reader = new FileInputStream(file);
    	// Read the compress file using GZIPInputStream way
    	GZIPInputStream readZip = new GZIPInputStream(reader);
    	// Only 8192 byte can be read in once
    	byte[] buffer = new byte[8192];
    	// Define the temp file
    	File tempfile = new File(file.toString().substring(0, file.toString().lastIndexOf("."))+".svg");
    	FileOutputStream writer = new FileOutputStream(tempfile);
        int n;
        
        // Read the zip file and write it to the temp file 
        while ((n = readZip.read(buffer, 0, 8192)) != -1)
          writer.write(buffer, 0, n);
        writer.close();
        readZip.close();

    	frame.openFile(tempfile);
    	frame.setTempfile(tempfile);
    }


}
